package com.micro.ai.files.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.files.entity.FileShare;
import com.micro.ai.files.service.FileShareService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 文件分享控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/file-shares")
@Tag(name = "文件分享管理", description = "文件分享的创建、查询、取消等功能")
public class FileShareController {

    @Autowired
    private FileShareService fileShareService;

    @PostMapping
    @PreAuthorize("hasAuthority('file_share:create')")
    @Operation(summary = "创建文件分享", description = "创建新的文件分享")
    public ApiResponse<FileShare> create(@Valid @RequestBody FileShare share) {
        FileShare result = fileShareService.create(share);
        return ApiResponse.success("创建成功", result);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('file_share:update')")
    @Operation(summary = "更新文件分享", description = "更新文件分享信息")
    public ApiResponse<FileShare> update(
            @Parameter(description = "分享ID", required = true) @PathVariable String id,
            @Valid @RequestBody FileShare share) {
        FileShare result = fileShareService.update(id, share);
        return ApiResponse.success("更新成功", result);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('file_share:delete')")
    @Operation(summary = "取消分享", description = "取消文件分享")
    public ApiResponse<Void> delete(
            @Parameter(description = "分享ID", required = true) @PathVariable String id) {
        fileShareService.delete(id);
        return ApiResponse.successVoid("取消分享成功");
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('file_share:view')")
    @Operation(summary = "获取分享详情", description = "根据ID获取分享详细信息")
    public ApiResponse<FileShare> getById(
            @Parameter(description = "分享ID", required = true) @PathVariable String id) {
        FileShare share = fileShareService.getById(id);
        if (share == null) {
            return ApiResponse.error("F0002", "文件分享不存在");
        }
        return ApiResponse.success(share);
    }

    @GetMapping("/token/{shareToken}")
    @Operation(summary = "根据分享令牌获取分享信息", description = "公开接口，根据分享令牌获取分享信息")
    public ApiResponse<FileShare> getByShareToken(
            @Parameter(description = "分享令牌", required = true) @PathVariable String shareToken) {
        FileShare share = fileShareService.getByShareToken(shareToken);
        if (share == null) {
            return ApiResponse.error("F0002", "分享不存在或已过期");
        }
        return ApiResponse.success(share);
    }

    @PostMapping("/validate-password")
    @Operation(summary = "验证分享密码", description = "公开接口，验证分享密码")
    public ApiResponse<Boolean> validatePassword(
            @Parameter(description = "分享令牌", required = true) @RequestParam("shareToken") String shareToken,
            @Parameter(description = "密码", required = true) @RequestParam("password") String password) {
        boolean valid = fileShareService.validateSharePassword(shareToken, password);
        return ApiResponse.success(valid);
    }

    @PutMapping("/{id}/increment-download")
    @Operation(summary = "增加下载次数", description = "增加分享的下载次数")
    public ApiResponse<Void> incrementDownloadCount(
            @Parameter(description = "分享ID", required = true) @PathVariable String id) {
        fileShareService.incrementDownloadCount(id);
        return ApiResponse.successVoid("更新成功");
    }

    @PutMapping("/{id}/increment-view")
    @Operation(summary = "增加预览次数", description = "增加分享的预览次数")
    public ApiResponse<Void> incrementViewCount(
            @Parameter(description = "分享ID", required = true) @PathVariable String id) {
        fileShareService.incrementViewCount(id);
        return ApiResponse.successVoid("更新成功");
    }

    @GetMapping("/page")
    @PreAuthorize("hasAuthority('file_share:view')")
    @Operation(summary = "分页查询分享列表", description = "支持多条件查询分享列表")
    public ApiResponse<Page<FileShare>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(value = "tenantId", required = false) String tenantId,
            @Parameter(description = "文件ID") @RequestParam(value = "fileId", required = false) String fileId,
            @Parameter(description = "创建人ID") @RequestParam(value = "createdBy", required = false) String createdBy) {
        Page<FileShare> page = fileShareService.pageQuery(pageNum, pageSize, tenantId, fileId, createdBy);
        return ApiResponse.success(page);
    }

    @GetMapping("/by-file/{fileId}")
    @PreAuthorize("hasAuthority('file_share:view')")
    @Operation(summary = "查询文件的分享列表", description = "根据文件ID查询分享列表")
    public ApiResponse<List<FileShare>> listByFileId(
            @Parameter(description = "文件ID", required = true) @PathVariable String fileId) {
        List<FileShare> list = fileShareService.listByFileId(fileId);
        return ApiResponse.success(list);
    }

    @GetMapping("/by-user")
    @PreAuthorize("hasAuthority('file_share:view')")
    @Operation(summary = "查询用户的分享列表", description = "根据用户ID查询分享列表")
    public ApiResponse<List<FileShare>> listByCreatedBy(
            @Parameter(description = "租户ID", required = true) @RequestParam("tenantId") String tenantId,
            @Parameter(description = "创建人ID", required = true) @RequestParam("createdBy") String createdBy) {
        List<FileShare> list = fileShareService.listByCreatedBy(tenantId, createdBy);
        return ApiResponse.success(list);
    }
}

